package com.itheima.reggie.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.util.AliyunSmsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 发送验证码
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody User user, HttpSession session){
        String phone = user.getPhone();
        if (StrUtil.isEmpty(phone)){
            return R.error("手机号不能为空!");
        }
        String code = RandomUtil.randomNumbers(6);
        AliyunSmsUtil.sendSms2(phone,code);
        session.setAttribute(phone,code);
        return R.success("验证码发送成功!");
    }

    /**
     * 客户端登录
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody Map<String,String> user, HttpSession session){
        String phone = user.get("phone");
        String code = user.get("code");
        if (StrUtil.isEmpty(phone) || StrUtil.isEmpty(code)){
            return R.error("手机号或验证码不能为空!");
        }
        //获取服务器端存储的真实的验证码
        String realCode = (String) session.getAttribute(phone);
        //验证码只能使用一次,验证码从session中销毁
        session.removeAttribute(phone);
        if (code.equals(realCode)){
            //登录成功
            //判断该手机号是否已注册,如果没有注册,自动注册到User表中
            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
            lqw.eq(User::getPhone,phone);
            User one = userService.getOne(lqw);
            if (one == null){
                one = new User();
                one.setPhone(phone);
                one.setStatus(1);
                userService.save(one);
            }
            //存储用户信息到session中
            session.setAttribute("loginUser",one);
            return R.success("登录成功!");
        }else {
            //登陆失败
            return R.error("验证码错误!");
        }
    }

    /**
     * 客户端退出登录
     * @param session
     * @return
     */
    @PostMapping("/loginout")
    public R loginOut(HttpSession session){
        session.removeAttribute("loginUser");
        return R.success("退出成功");
    }
}
